<template>
  <div>
    <Breadcrumb :opt-data="userOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="userData"
          :custom-empty="true"
          @pageChanged="getUserData"
          @sizeChanged="getUserData"
          @filterChange="getUserData">
          <EmptyContent slot="empty" :opt-data="userOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog
        :title="`${!isEditUser ? '新增' : '编辑'}用户`"
        :visible.sync="showUserDialog"
        :close-on-click-modal="false"
        width="600px"
        center>
        <el-form
          v-loading="userFormLoading"
          :ref="userFormRef"
          :model="userForm"
          :rules="userFormRules"
          size="small"
          label-width="130px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" placeholder="请填写用户名"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userForm.name" placeholder="请填写姓名"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userForm.nickname" placeholder="请填写昵称"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="tel">
            <el-input v-model="userForm.tel" placeholder="请填写电话"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userForm.email" placeholder="请填写邮箱"></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="userForm.role" placeholder="请选择角色" class="width-100">
              <el-option label="用户" value="guest"></el-option>
              <el-option label="管理员" value="admin"></el-option>
              <el-option label="运维人员" value="user"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="公司名称" prop="company" v-if="userForm.role === 'guest'">
            <el-input v-model="userForm.company" placeholder="请填写公司名称"></el-input>
          </el-form-item>
          <el-form-item label="职务" prop="job"  v-if="userForm.role === 'guest'">
            <el-input v-model="userForm.job" placeholder="请填写职务"></el-input>
          </el-form-item>
          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="userFormCanceled">取消</el-button>
              <el-button size="medium" type="primary" @click="userFormSubmitted">提交</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {msgCode} from "@/config/string";
  import {userRole} from "@/config/common";
  import {messageHandle, confirmHandle, deepCopyWithJson, getUserInfo} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import userTableCfg from "../../config/table/user";
  import EZTable from '../../components/table/EZTable';

  export default {
    name: "UserManagement",
    components: {
      EZTable
    },
    data() {
      return {
        tableId: tableIdConfig.user,
        tableLoading: true,
        tableHdl: null,
        userData: [],
        showUserDialog: false,
        userFormLoading: false,
        userFormRef: 'userFormRef',
        userForm: {
          username: '',
          name: '',
          nickname: '',
          tel: '',
          email: '',
          role: 'user',
          company: '',
          job: '',
        },
        userFormRules: {
          username: [
            {required: true, message: '请填写用户名', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请填写姓名', trigger: 'blur'}
          ],
          nickname: [
            {required: true, message: '请填写昵称', trigger: 'blur'}
          ],
          tel: [
            {required: true, message: '请填写电话', trigger: 'blur'}
          ],
          company: [
            {required: true, message: '请填写公司名称', trigger: 'blur'}
          ],
          job: [
            {required: true, message: '请填写职务', trigger: 'blur'}
          ],
        },
        isEditUser: false,
        userRole:userRole
      }
    },
    computed: {
      userOptData() {
        return [
          {
            type: 'btn',
            label: '新增用户',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          },
        ];
      }
    },
    activated() {
      this.initTableConfig();
      this.initUserForm();
      this.getUserData();
    },
    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, userTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const user = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showUserDialog = true;
              this.isEditUser = true;
              this.userForm = user;
              break;
            case tableOptBtnConfig.resetPwd.type:
              this.resetUserPwd(user);
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteUser(user);
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      initUserForm() {
        this.userForm = {
          username: '',
          name: '',
          nickname: '',
          tel: '',
          email: '',
          role: 'user',
          company: '',
          job: '',
        };
      },
      resetUserForm() {
        this.initUserForm();
        const userForm = this.$refs[this.userFormRef];
        userForm && userForm.resetFields();
      },
      clickCreateBtn() {
        this.isEditUser && this.resetUserForm();
        this.showUserDialog = true;
        this.isEditUser = false;
      },
      getUserData() {
        this.tableLoading = true;
        const tableParam = this.tableHdl.assembleTableParam();
        API.user.userList(tableParam).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;

          this.userData = data.map(d => {
            const roleText = this.userRole.find(type => type.value === d.role) || {};
            return {
              ...d,
              roleText:roleText.label,
              isAdminText: `<span class="font-color-success">${d.isAdmin ? '是' : '否'}</span>`
            }
          });
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      resetUserPwd(user = {}) {
        confirmHandle({label: `确定要重置用户：${user.name} 的登录密码吗?`}).then(() => {
          API.user.userResetPwd({userId: user._id}).then(result => {
            messageHandle({code: msgCode.OPERATE_SUCCESS, title: '用户'});
          });
        }).catch(() => {
        });
      },
      deleteUser(user = {}) {
        confirmHandle({label: `确定要删除用户：${user.name} 吗?`}).then(() => {
          API.user.userDelete({_id: user._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '用户'});
            this.tableHdl.judgeTableMatched();
            this.getUserData();
          });
        }).catch(() => {
        });
      },
      userFormCanceled() {
        this.showUserDialog = false;
      },
      userFormSubmitted() {
        this.$refs[this.userFormRef].validate((valid) => {
          if (!valid) return;
          this.userFormLoading = true;
          if (!this.isEditUser) {
            API.user.userAdd(this.userForm).then(result => {
              messageHandle({code: msgCode.ADD_SUCCESS, title: '用户'});
              this.showUserDialog = false;
              this.userFormLoading = false;
              this.getUserData();
              this.resetUserForm();
            }).catch(err => {
              console.log('err', err)
              this.userFormLoading = false;
            });
          } else {
            API.user.userEdit(this.userForm).then(result => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '用户'});
              this.showUserDialog = false;
              this.userFormLoading = false;
              this.getUserData();
              this.resetUserForm();
            }).catch(err => {
              console.log('err', err)
              this.userFormLoading = false;
            });
          }
        });
      },
    },
  }
</script>

<style scoped>

</style>
